#!/usr/bin/env bash
# ==============================================================================
# What:
# - converts a local site's metadata from plain XML ($INPUT) to RIF-CS ($RIFCS)
#   using the stylesheet at $XSLT_RIFCS, and then to muRIFCS ($OUTPUT) using the
#   stylesheet at $XSLT_muRIFCS
# - transformation scenario as follows: plain XML > RIF-CS > muRIFCS
# - uses Saxon as the conversion tool
# ==============================================================================
export SELF=${0##*/}
export BASE_DIR=${BASE_DIR:-"$( cd "$( dirname "$0" )" && pwd )"}
source ${BASE_DIR}/local2rdr.profile

# Configurable parameters
# - uses definitions from local2rdr.profile by default
export CLASS_PATH=".:${SAXON_JAR}:${CLASS_PATH}"
export INPUT=${XML2MURIFCS_INPUT}
export RIFCS=${XML2MURIFCS_RIFCS}
export OUTPUT=${XML2MURFICS_OUTPUT}
export XSLT_RIFCS=${XML2MURIFCS_XSLT_RIFCS}
export XSLT_muRIFCS=${XML2MURIFCS_XSLT_muRIFCS}

# Select desired XML Transform Scenario
# 1 = local XML > RIF-CS > muRIFCS
# 2 = RIF-CS > muRIFCS
export TARGET_TRANSFORM=${TARGET_TRANSFORM:-1}

case "$TARGET_TRANSFORM" in
  1) TARGET_INPUT=${INPUT} ;;
  2) TARGET_INPUT=${RIFCS} ;;
esac


echo
echo "  executing ${SELF} ..."

if [[ -e ${TARGET_INPUT} ]]
then
   case $TARGET_TRANSFORM in
      1) # Transform 1
         $SAXON_HOME/saxon.sh ${INPUT} ${RIFCS} ${XSLT_RIFCS} && \
         $SAXON_HOME/saxon.sh ${RIFCS} ${OUTPUT} ${XSLT_muRIFCS}
         ;;
      2) # Transform 2
         $SAXON_HOME/saxon.sh ${RIFCS} ${OUTPUT} ${XSLT_muRIFCS}
         ;;
      *) # Unsupported Transform number
         echo "  error: unsupported Transform number: ${TARGET_TRANSFORM}"
         echo
         exit 1
         ;;
   esac

   if [[ $? = 0 ]]
   then
      echo "  finished: completed conversion of"
      echo "    ${TARGET_INPUT}"
      echo "   to"
      echo "    ${OUTPUT}"
      echo
      exit 0
   else
      echo "  failure: some error occurred"
      echo
      exit 1
   fi
else 
   echo "  error: missing input file: ${TARGET_INPUT}"
   echo
   exit 1
fi